﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using GroceryList.Domain.Mapping;
using GroceryList.Domain.Model.Product;
using GroceryList.Front.Web.Helpers;
using GroceryList.Model;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace GroceryList.Test
{
    public class BaseServiceTest
    {
        public BaseServiceTest()
        {
            var cfg = DeleteAndCreateDatabase();
            ExecuteSqlScriptFromScriptToTestFolder(cfg);
        }

        private static void ExecuteSqlScriptFromScriptToTestFolder(Configuration cfg)
        {
            using (var conn = new SqlConnection(cfg.GetProperty("connection.connection_string")))
            {
                var scriptToTestPath = GetScriptToTestPath();

                var ficheros = GeOnlySqlFiles(scriptToTestPath);

                foreach (var fichero in ficheros)
                {
                    var file = new FileInfo(fichero);
                    var script = file.OpenText().ReadToEnd();
                    var command = new SqlCommand(script, conn);
                    if(conn.State!=ConnectionState.Open)
                        conn.Open();
                    command.ExecuteNonQuery();

                }
            }
        }

        private static IEnumerable<string> GeOnlySqlFiles(string scriptToTestPath)
        {
            return Directory.GetFiles(String.Format("{0}{1}", scriptToTestPath, Path.DirectorySeparatorChar), "*.sql");
        }

        private static string GetScriptToTestPath()
        {
            var strFilePath = Directory.GetCurrentDirectory();
            strFilePath = Directory.GetParent(strFilePath).ToString();
            strFilePath = Directory.GetParent(strFilePath).ToString();
            strFilePath = Directory.GetParent(strFilePath).ToString();
            strFilePath = Directory.GetParent(strFilePath).ToString();
            return String.Format("{0}{1}{2}", strFilePath, Path.DirectorySeparatorChar, "ScriptToTest");
        }

        private static Configuration DeleteAndCreateDatabase()
        {
            var cfg = new Configuration();
            cfg.Configure();
            cfg.AddAssembly(typeof(Producto).Assembly);
            cfg.AddDeserializedMapping(NhMappingHelper.GetCompiledMappingFromAssembly(typeof(ListaCompraMap)), "Identifier");
            new SchemaExport(cfg).Execute(false, true, false);
            return cfg;
        }
    }
}